package drds.plus.common.model.comparative;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.util.ArrayList;

/**
 * Comparative List,作用是持有多个Comparative，是对and 节点和or节点的一种公共抽象。
 */
@Slf4j
public abstract class List extends Comparative {

    protected java.util.List<Comparative> comparativeList = new ArrayList<Comparative>(2);

    public List(int function, Comparable<?> value) {
        super(function, value);
        comparativeList.add(new Comparative(function, value));
    }

    protected List() {
        super();
    }

    public List(int capacity) {
        super();
        comparativeList = new ArrayList<Comparative>(capacity);
    }

    public List(Comparative item) {
        super(item.getComparison(), item.getValue());
        comparativeList.add(item);
    }

    public java.util.List<Comparative> getComparativeList() {
        return comparativeList;
    }

    public void addComparative(Comparative item) {
        this.comparativeList.add(item);
    }

    public Object clone() {
        try {
            Constructor<? extends List> con = this.getClass().getConstructor((Class[]) null);
            List compList = con.newInstance((Object[]) null);
            for (Comparative comparative : comparativeList) {
                compList.addComparative((Comparative) comparative.clone());
            }
            compList.setComparison(this.getComparison());
            compList.setValue(this.getValue());
            return compList;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }

    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        boolean firstElement = true;
        for (Comparative comp : comparativeList) {
            if (!firstElement) {
                sb.append(getRelation());
            }
            sb.append(comp.toString());
            firstElement = false;
        }
        return sb.toString();
    }

    abstract protected String getRelation();
}
